<template>
  <div class="CityView">
    <!-- <van-index-bar>
      <van-index-anchor index="A" />
      <van-cell title="文本" />
      <van-cell title="文本" />
      <van-cell title="文本" />

    </van-index-bar> -->
    <van-index-bar :index-list="indexList">
      <!-- 定位城市 -->
      <van-index-anchor index="定位城市" />
      <van-cell v-if="nowCity" :title="nowCity" @click="selectCity(nowCity)" />
      <van-cell class="nowcity" v-else title="定位失败，请稍后重试" />

      <!-- 最近访问城市 -->
      <van-index-anchor index="最近访问城市" />
      <div class="box" v-if="selectCityHistory != []">
        <van-cell
          v-for="(item, index) in selectCityHistory"
          :key="index"
          class="hotvancell"
          :title="item.nm"
          @click="selectCity(item)"
        />
      </div>

      <!-- 热门城市 -->
      <van-index-anchor index="热门城市" />
      <div class="box">
        <van-cell
          class="hotvancell"
          v-for="item in parsedHot"
          :key="item.id"
          :title="item.nm"
          @click="selectCity(item)"
        />
      </div>

      <!-- 城市分类 -->
      <template v-for="item in parsedCities">
        <van-index-anchor :key="item.letter" :index="item.letter" />
        <van-cell
          class="city"
          v-for="city in item.cities"
          :key="city.id"
          :title="city.nm"
          @click="selectCity(city)"
        />
      </template>
    </van-index-bar>
  </div>
</template>
<script>

export default {
  data() {
    return {
      hot: [],
      cts: [],
      nowCity: "",
      selectCityHistory: [],
      //把数据处理成以下形式
      test: [
        {
          letter: "A",
          cities: [
            {
              id: 1,
              nm: "阿拉蕾",
              py: "alalei",
            },
            {
              id: 2,
              nm: "阿拉蕾",
              py: "alalei",
            },
            {
              id: 3,
              nm: "阿拉蕾",
              py: "alalei",
            },
          ],
        },
        {
          letter: "B",
          cities: [
            {
              id: 4,
              nm: "吧拉蕾",
              py: "balalei",
            },
            {
              id: 5,
              nm: "吧拉蕾",
              py: "balalei",
            },
            {
              id: 6,
              nm: "吧拉蕾",
              py: "balalei",
            },
          ],
        },
      ],
    };
  },
  created() {
    //   获取定位
    navigator.geolocation.getCurrentPosition((position) => {
      console.log("获取到位置", position.coords);
      // 经度：${position.coords.longitude} 纬度：${position.coords.latitude}
      this.$axios
        .get(
          `https://apis.netstart.cn/maoyan/city/latlng?lat=${position.coords.latitude}&lng=${position.coords.longitude} `
        )
        .then((res) => {
          console.log(
            "根据经纬度定位获取到当前城市信息",
            res.data.data.openCityName
          );
          // var obj = {};
          // obj.id = res.data.data.id;
          // obj.nm = res.data.data.openCityName;
          this.nowCity = res.data.data.openCityName;
        });
    });
    // 获取最近访问城市（本地历史记录）
    this.getHistory();
    //  获取城市名列表
    this.$axios
      .get("https://apis.netstart.cn/maoyan/cities.json")
      .then((res) => {
        console.log(res);
        this.hot = res.data.hot;
        this.cts = res.data.cts;
      });
  },

  methods: {
    // 点击某个城市后触发的方法
    selectCity(city) {
      // console.log(city);
      // 把历史记录存到本地
      this.setHistory(city);
      // 获取最近访问城市（本地历史记录）
      this.getHistory();
      this.$router.go(-1);
    },
    // 把历史记录存到本地方法
    setHistory(city) {
      let re = localStorage.getItem("selecthistory");
      if (!re) {
        //第一次添加历史记录的时候
        let cityHistory = [];
        cityHistory.unshift(city);
        // 历史记录去重
        for (var i = 0; i < cityHistory.length; i++) {
          for (var j = i + 1; j < cityHistory.length; j++) {
            if (cityHistory[i].id == cityHistory[j].id) {
              cityHistory.splice(j, 1);
              //因为数组裁切以后，后一项的下标会往前进1（会修改原数组）
              //所以这个元素需要重新判断一次
              j--;
            }
          }
        }
        localStorage.setItem("selecthistory", JSON.stringify(cityHistory));
      } else {
        //非第一次添加历史记录的时候
        //还原成数组
        let cityHistory = JSON.parse(re);
        cityHistory.unshift(city);
        for (var a = 0; a < cityHistory.length; a++) {
          for (var b = a + 1; b < cityHistory.length; b++) {
            if (cityHistory[a].id == cityHistory[b].id) {
              cityHistory.splice(b, 1);
              //因为数组裁切以后，后一项的下标会往前进1（会修改原数组）
              //所以这个元素需要重新判断一次
              b--;
            }
          }
        }
        localStorage.setItem("selecthistory", JSON.stringify(cityHistory));
      }
    },
    // 获取历史记录方法
    getHistory() {
      //获取历史记录
      let re = localStorage.getItem("selecthistory");
      this.selectCityHistory = JSON.parse(re);
    },
  },
  computed: {
    parsedCities() {
      var obj = {};
      this.cts.forEach((element) => {
        // 取每个城市拼音的首字母并转为大写
        var letter = element.py.slice(0, 1).toUpperCase();
        if (obj[letter]) {
          // 存在
          obj[letter] = [...obj[letter], element];
        } else {
          // 不存在
          obj[letter] = [element];
        }
      });
      var arr = [];
      for (var key in obj) {
        arr.push({
          letter: key,
          cities: obj[key],
        });
      }
      var newArr = arr.sort(function (a, b) {
        return a.letter.charCodeAt(0) - b.letter.charCodeAt(0);
      });
      //   需要按照对象数组里面的每一项 对象的每个值
      return newArr;
    },
    indexList() {
      return [
        "定位",
        "最近",
        "热门",
        ...this.parsedCities.map((o) => o.letter),
      ];
    },
    parsedHot() {
      return this.hot.map((element) => this.cts.find((o) => o.nm === element));
    },
  },
};
</script>
<style lang="less">
// 改变高亮颜色
.van-index-bar__index--active {
  color: #e54847;
}
// 改变索引行背景颜色
.van-index-anchor {
  background-color: #ebebeb !important;
}
// 改变城市栏背景颜色
.van-cell {
  background-color: #f5f5f5;
}
// 定位城市
.nowcity {
  display: block;
  background-color: #f5f5f5 !important;
}
.nowcity .van-cell__title {
  padding: 5px 25px;
  display: inline-block;
  border: 1px solid #ebedf0;
  background-color: #ffffff;
  border-radius: 4px;
}
.nowcity .van-cell__title span {
  display: inline-block;
  text-align: center;
  line-height: 15px;
}
// 热门城市(最近访问城市样式和热门城市一样，直接复用)
.box {
  padding: 16px 22px 0 16px;
  display: flex;
  background-color: #f5f5f5;
  flex-wrap: wrap;
}
.hotvancell {
  text-align: center;
  line-height: 15px !important;
  width: 30% !important;
  height: 35px;
  border: 1px solid #ebedf0;
  background-color: #ffffff;
  margin: 0 10px 15px 0;
  border-radius: 4px;
}
// 城市分类
.city {
  padding-bottom: 0;
  padding-right: 35px;
}
.city .van-cell__title {
  display: inline-block;
  padding: 0 0 10px 0;
  border-bottom: 2px solid #d8d7da;
}
// 右边索引
.van-index-bar__index {
  margin-bottom: 5px;
}
</style>